<template>
	<view class="classroom-select">
		<cc-navbar></cc-navbar>
		<view class="list" v-if="count">
			<view class="list-item cc-text-32 cc-text-600" :class="[{ 'list-item-check': item.check }]"
				@tap="handleClick(item)" v-for="(item, index) in list" :key="index">
				{{ item.name }}
			</view>
			<cc-loadmore show-limit="10" :loading="loading" :current="list.length" :count="count" />
			<cc-empty v-if="!loading && !count" mode="list" />
			<view class="footer">
				<view class="placeholder">
					<u-gap height="108rpx"></u-gap>
					<u-safe-bottom></u-safe-bottom>
				</view>
				<view class="footer-content">
					<view class="fcb">
						<view class="footer-content-action-left">
							<text class="font-info mb10">已选择教室</text>
							<text>{{ currentCheckItem.name || '-' }}</text>
						</view>
						<u-button custom-style="width: 284rpx;" :disabled="!currentCheckItem.id" type="primary"
							:text="currentCheckItem.id ? '确认选择' : '请选择教室'" @click="handleConfirm"></u-button>
					</view>
					<u-safe-bottom></u-safe-bottom>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	/**
	 * 教室选择
	 * 单选，没分页
	 */
	import {
		roomList
	} from '@/codecat/api/common';
	export default {
		computed: {
			count() {
				return this.list.length || 0;
			},
			currentCheckItem() {
				let result = {};
				if (this.list.length) {
					result = this.list.find((e) => e.check) || {};
				}
				return result;
			}
		},
		data() {
			return {
				id: '',
				loading: false,
				list: []
			};
		},
		onLoad() {
			const options = this.$Route.query;
			this.id = options?.id || '';
			this.getList();
		},
		methods: {
			handleConfirm() {
				const pages = getCurrentPages();
				if (pages.length > 1) {
					if (this.id !== this.currentCheckItem.id) {
						const prevPage = pages[pages.length - 2]; // 上一个页面
						prevPage.$vm.classRoomSelect(this.currentCheckItem);
					}
					uni.navigateBack({
						delta: 1
					});
				}
			},
			handleClick(item) {
				this.$lodash.forEach(this.list, (e) => {
					e.check = item.id === e.id;
				});
			},
			getList() {
				this.loading = true;
				roomList()
					.then((res) => {
						this.loading = false;
						if (Array.isArray(res.data) && res.data.length) {
							this.$lodash.forEach(res.data, (e) => {
								e.check = e.id === this.id;
							});
							this.list = res.data;
						}
					})
					.catch((_) => {
						this.loading = false;
					});
			}
		}
	};
</script>

<style lang="scss" scoped>
	@import './index.scss';
</style>